﻿

using Microsoft.Extensions.Configuration;
using Orleans.Placement;
using Orleans.Runtime.Placement;
using Orleans.Runtime;
using Orleans.Concurrency;
using Grain.Strategy;
using Orleans.Providers;

namespace OrleansDemo.Grain
{
    [StorageProvider(ProviderName = "OrleansStorage")]
    // [SamplePlacementStrategy]
    // [StatelessWorker]
    public class HelloGrain : Orleans.Grain<HelloGrainState>, IHello
    {
        public static string ServerId { get; set; }

        private int _count = 0;

        private List<string> _list { get; set; }

        public HelloGrain()
        {

        }

        public async Task<string> SayHello(string greeting)
        {
            await Task.Delay(10);
            // await Task.Delay(260000);
            //Console.WriteLine($"{ServerId} SayHello message received: greeting = '{greeting}'");
            //this.State.Count++;
            //await this.WriteStateAsync();
            this._list.Add("abc");
            return $" {ServerId} You said: '{greeting}', I say: Hello! count={this._list.Count}";
        }

        public override async Task OnActivateAsync(CancellationToken cancellationToken)
        {
            await this.ReadStateAsync();
            _list = this.State.List;
            await base.OnActivateAsync(cancellationToken);
        }

        public override async Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken)
        {
            this.State.List = _list;
            await this.WriteStateAsync();
            await base.OnDeactivateAsync(reason, cancellationToken);
        }
    }

    public class HelloGrainState
    {
        public List<string> List { get; set; } = new List<string>();
    }
}
